import { loginIgnore } from '@/router/index'
import { checkAuthorization } from '@/utils/request'
import NProgress from 'nprogress'
// import { getRoutesConfig } from '@/services/user'
import { loadRoutes } from '@/utils/routerUtil'
NProgress.configure({ showSpinner: false })
import store from '@/store'
/**
 * 进度条开始
 * @param to
 * @param form
 * @param next
 */
const progressStart = (to, from, next) => {
  // start progress bar
  if (!NProgress.isStarted()) {
    NProgress.start()
  }
  next()
}

/**
 * 登录守卫
 * @param to
 * @param form
 * @param next
 * @param options
 */
const loginGuard = async(to, from, next) => {
  const enableSSO = store.state.setting.enableSSO
  const loginPath = enableSSO ? '/loginsso1' : '/login'
  // 修改路由跳转重定向逻辑
  if (checkAuthorization()) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (store.getters['account/routesConfig'].length === 0) {
        try {
          store.dispatch('account/GetAuth')// 获取用户权限
          const routesConfig = await store.dispatch('account/GetRoutes') // 获取动态路由
          loadRoutes(routesConfig) // 组装动态路由与静态路由
          const redirect = decodeURIComponent(from.query.redirect || to.path)
          if (to.path === redirect) {
            next({ ...to, replace: true })
          } else {
            // 跳转到目的路由
            next({ path: redirect })
          }
        } catch (error) {
          store.commit('account/clearStorage')
          next({ path: loginPath, query: { redirect: to.fullPath }})
          NProgress.done()
          console.error(error)
        }
      } else {
        next()
      }
    }
  } else {
    if (!loginIgnore.includes(to)) {
      next({ path: loginPath, query: { redirect: to.fullPath }})
    } else {
      next()
    }
  }
}

/**
 * 混合导航模式下一级菜单跳转重定向
 * @param to
 * @param from
 * @param next
 * @param options
 * @returns {*}
 */
const redirectGuard = (to, from, next, options) => {
  const { store } = options
  const getFirstChild = (routes) => {
    const route = routes[0]
    if (!route.children || route.children.length === 0) {
      return route
    }
    return getFirstChild(route.children)
  }
  if (store.state.setting.layout === 'mix') {
    const firstMenu = store.getters['setting/firstMenu']
    if (firstMenu.find(item => item.fullPath === to.fullPath)) {
      store.commit('setting/setActivatedFirst', to.fullPath)
      const subMenu = store.getters['setting/subMenu']
      if (subMenu.length > 0) {
        const redirect = getFirstChild(subMenu)
        return next({ path: redirect.fullPath })
      }
    }
  }
  next()
}

/**
 * 进度条结束
 * @param to
 * @param form
 * @param options
 */
const progressDone = () => {
  // finish progress bar
  NProgress.done()
}

export default {
  beforeEach: [progressStart, loginGuard, redirectGuard],
  afterEach: [progressDone]
}
